<template>
  <div class="page-container">
    <!-- 统计卡片 -->
    <CommentStats ref="statsRef" />
    
    <el-card class="card-container">
      <template #header>
        <div class="card-header">
          <span>评论管理</span>
          <el-button 
            v-if="commentPublishEnabled" 
            type="primary" 
            @click="handleAdd"
          >
            <el-icon><Plus /></el-icon>
            新增评论
          </el-button>
          <el-tag 
            v-else 
            type="danger" 
            size="small"
            style="margin-left: 10px;"
          >
            评论发布功能已禁用
          </el-tag>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="searchForm" inline>
          <el-form-item label="用户ID">
            <el-input
              v-model="searchForm.userId"
              placeholder="请输入用户ID"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="文章ID">
            <el-input
              v-model="searchForm.articleId"
              placeholder="请输入文章ID"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="父评论ID">
            <el-input
              v-model="searchForm.parentId"
              placeholder="请输入父评论ID"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option label="待审核" :value="0" />
              <el-option label="已通过" :value="1" />
              <el-option label="已拒绝" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="评论内容">
            <el-input
              v-model="searchForm.content"
              placeholder="请输入关键词"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 操作按钮区域 -->
      <div class="action-container">
        <div class="batch-actions">
          <el-button 
            type="danger" 
            @click="handleBatchDelete" 
            :disabled="selectedIds.length === 0"
          >
            <el-icon><Delete /></el-icon>
            批量删除 ({{ selectedIds.length }})
          </el-button>
          
          <el-button 
            type="success" 
            @click="handleBatchAudit(1)" 
            :disabled="selectedIds.length === 0"
          >
            <el-icon><Check /></el-icon>
            批量通过 ({{ selectedIds.length }})
          </el-button>
          
          <el-button 
            type="warning" 
            @click="handleBatchAudit(2)" 
            :disabled="selectedIds.length === 0"
          >
            <el-icon><Close /></el-icon>
            批量拒绝 ({{ selectedIds.length }})
          </el-button>
          
          <el-dropdown @command="handleBatchMoreAction" :disabled="selectedIds.length === 0">
            <el-button :disabled="selectedIds.length === 0">
              更多操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="export" icon="Download">
                  导出选中评论
                </el-dropdown-item>
                <el-dropdown-item command="move" icon="Promotion">
                  移动到其他文章
                </el-dropdown-item>
                <el-dropdown-item divided></el-dropdown-item>
                <el-dropdown-item command="mark-read" icon="View">
                  标记为已查看
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        
        <div class="quick-actions">
          <el-button @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          
          <el-button @click="handleExportAll">
            <el-icon><Download /></el-icon>
            导出全部
          </el-button>
          
          <el-button @click="showAdvancedSearch = !showAdvancedSearch">
            <el-icon><Search /></el-icon>
            {{ showAdvancedSearch ? '隐藏' : '高级' }}搜索
          </el-button>
        </div>
      </div>
      
      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="commentList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="content" label="评论内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="userName" label="评论用户" width="120">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar v-if="row.userAvatar" :src="row.userAvatar" :size="24" style="margin-right: 8px" />
              <span>{{ row.userName || '未知用户' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="articleTitle" label="所属文章" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="article-info">
              <div class="article-title">{{ row.articleTitle || '未知文章' }}</div>
              <div class="article-category" v-if="row.categoryName">
                <el-tag type="info" size="small">{{ row.categoryName }}</el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="articleTags" label="文章标签" width="200">
          <template #default="{ row }">
            <div class="tags-container" v-if="row.articleTags && row.articleTags.length > 0">
              <el-tag 
                v-for="tag in row.articleTags.slice(0, 3)" 
                :key="tag.id" 
                size="small" 
                :color="tag.color"
                style="margin-right: 4px; margin-bottom: 2px;"
              >
                {{ tag.name }}
              </el-tag>
              <el-tooltip v-if="row.articleTags.length > 3" content="查看更多标签">
                <el-tag size="small" type="info">+{{ row.articleTags.length - 3 }}</el-tag>
              </el-tooltip>
            </div>
            <span v-else class="no-tags">无标签</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusTagType(row.status)" 
              size="small"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="likeCount" label="点赞数" width="80">
          <template #default="{ row }">
            <span class="like-count">
              <el-icon><StarFilled /></el-icon>
              {{ row.likeCount || 0 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="parentContent" label="父评论" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <div v-if="row.parentContent" class="parent-comment">
              <el-tag type="warning" size="small">回复</el-tag>
              <span class="parent-user">{{ row.parentUserName }}:</span>
              <span class="parent-text">{{ row.parentContent }}</span>
            </div>
            <el-tag v-else type="info" size="small">顶级评论</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <!-- 查看详情按钮 -->
              <el-tooltip content="查看详情" placement="top">
                <el-button 
                  type="info" 
                  size="small" 
                  circle
                  @click="handleViewDetail(row)"
                >
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>
              
              <!-- 编辑按钮 -->
              <el-tooltip content="编辑评论" placement="top">
                <el-button 
                  type="primary" 
                  size="small" 
                  circle
                  @click="handleEdit(row)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              
              <!-- 审核按钮组 - 仅待审核状态显示 -->
              <template v-if="row.status === 0">
                <el-tooltip content="审核通过" placement="top">
                  <el-button 
                    type="success" 
                    size="small" 
                    circle
                    @click="handleAudit(row, 1)"
                  >
                    <el-icon><Check /></el-icon>
                  </el-button>
                </el-tooltip>
                
                <el-tooltip content="审核拒绝" placement="top">
                  <el-button 
                    type="warning" 
                    size="small" 
                    circle
                    @click="handleAudit(row, 2)"
                  >
                    <el-icon><Close /></el-icon>
                  </el-button>
                </el-tooltip>
              </template>
              
              <!-- 点赞按钮 - 仅已通过评论显示 -->
              <el-tooltip v-if="row.status === 1" content="点赞评论" placement="top">
                <el-button 
                  type="warning" 
                  size="small" 
                  circle
                  @click="handleLike(row)"
                  :class="{ 'liked': row.likeCount > 0 }"
                >
                  <el-icon><StarFilled /></el-icon>
                </el-button>
              </el-tooltip>
              
              <!-- 回复按钮 - 仅已通过评论显示 -->
              <el-tooltip v-if="row.status === 1 && commentPublishEnabled" content="回复评论" placement="top">
                <el-button 
                  type="info" 
                  size="small" 
                  circle
                  @click="handleReply(row)"
                >
                  <el-icon><ChatDotRound /></el-icon>
                </el-button>
              </el-tooltip>
              
              <!-- 更多操作下拉菜单 -->
              <el-dropdown @command="(command) => handleMoreAction(command, row)" trigger="click">
                <el-button size="small" circle>
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <!-- 重新审核 - 仅已审核评论显示 -->
                    <el-dropdown-item 
                      v-if="row.status !== 0" 
                      command="reaudit"
                      icon="RefreshRight"
                    >
                      重新审核
                    </el-dropdown-item>
                    
                    <!-- 置顶/取消置顶 -->
                    <el-dropdown-item 
                      v-if="row.status === 1" 
                      :command="row.isTop ? 'untop' : 'top'"
                      :icon="row.isTop ? 'Bottom' : 'Top'"
                    >
                      {{ row.isTop ? '取消置顶' : '置顶评论' }}
                    </el-dropdown-item>
                    
                    <!-- 查看相关评论 -->
                    <el-dropdown-item 
                      command="related"
                      icon="Connection"
                    >
                      查看相关评论
                    </el-dropdown-item>
                    
                    <!-- 举报管理 -->
                    <el-dropdown-item 
                      v-if="row.reportCount > 0" 
                      command="reports"
                      icon="WarningFilled"
                    >
                      查看举报 ({{ row.reportCount }})
                    </el-dropdown-item>
                    
                    <el-dropdown-item divided></el-dropdown-item>
                    
                    <!-- 删除按钮 -->
                    <el-dropdown-item 
                      command="delete"
                      icon="Delete"
                      class="danger-item"
                    >
                      删除评论
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 评论编辑对话框 -->
    <CommentEdit
      v-model:visible="editDialogVisible"
      :comment="currentComment"
      :is-edit="isEdit"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getCommentList, 
  getCommentListWithRelations,
  createComment, 
  updateComment, 
  deleteComment, 
  batchDeleteComments,
  auditComment,
  likeComment,
  toggleCommentTop,
  batchAuditComments,
  getTopComments,
  reportComment,
  getCommentReports
} from '@/api/comment'
import { getUserList } from '@/api/user'
import { getArticleList } from '@/api/article'
import CommentEdit from './components/CommentEdit.vue'
import CommentStats from './components/CommentStats.vue'
import { getConfigStatus } from '@/api/system'

// 响应式数据
const loading = ref(false)
const commentList = ref([])
const selectedIds = ref([])
const editDialogVisible = ref(false)
const currentComment = ref({})
const isEdit = ref(false)
const statsRef = ref() // 统计组件引用

// 配置状态
const commentPublishEnabled = ref(true)
const showAdvancedSearch = ref(false)

// 搜索表单
const searchForm = reactive({
  userId: '',
  articleId: '',
  parentId: '',
  status: null,
  content: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 获取评论列表
const fetchCommentList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    console.log('开始获取评论列表，请求参数:', params)
    // 使用正确的API函数
    const result = await getCommentListWithRelations(params)
    console.log('评论列表响应结果:', result)
    
    if (result.code === 200) {
      commentList.value = result.data.records || []
      pagination.total = result.data.total || 0
      console.log('评论列表获取成功，数据量:', commentList.value.length, '总数:', pagination.total)
    } else {
      console.warn('评论列表响应异常:', result)
      commentList.value = []
      pagination.total = 0
      ElMessage.error(result.message || '获取评论列表失败')
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    commentList.value = []
    pagination.total = 0
    ElMessage.error('获取评论列表失败: ' + (error.message || error))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchCommentList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    userId: '',
    articleId: '',
    parentId: '',
    status: null,
    content: ''
  })
  pagination.page = 1
  fetchCommentList()
}

// 审核评论
const handleAudit = async (row, status) => {
  try {
    const statusText = status === 1 ? '通过' : '拒绝'
    await ElMessageBox.confirm(`确认${statusText}这条评论吗？`, '确认操作', {
      type: 'warning'
    })
    
    const response = await auditComment(row.id, status)
    if (response.code === 200) {
      ElMessage.success(`评论${statusText}成功`)
      await fetchCommentList()
      // 刷新统计信息
      if (statsRef.value) {
        statsRef.value.refreshStats()
      }
    } else {
      ElMessage.error(response.message || `评论${statusText}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`评论审核失败`)
    }
  }
}

// 点赞评论
const handleLike = async (row) => {
  try {
    const response = await likeComment(row.id)
    if (response.code === 200) {
      ElMessage.success('点赞成功')
      await fetchCommentList()
    } else {
      ElMessage.error(response.message || '点赞失败')
    }
  } catch (error) {
    ElMessage.error('点赞失败')
  }
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 0: return 'warning'  // 待审核
    case 1: return 'success'  // 已通过
    case 2: return 'danger'   // 已拒绝
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '已通过'
    case 2: return '已拒绝'
    default: return '未知'
  }
}

// 刷新
const handleRefresh = () => {
  fetchCommentList()
}

// 新增评论
const handleAdd = () => {
  isEdit.value = false
  currentComment.value = {}
  editDialogVisible.value = true
}

// 编辑评论
const handleEdit = (row) => {
  isEdit.value = true
  currentComment.value = { ...row }
  editDialogVisible.value = true
}

// 删除评论
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除这条评论吗？\n\n评论内容："${row.content.substring(0, 50)}${row.content.length > 50 ? '...' : ''}"`,
      '删除确认', 
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )
    
    const result = await deleteComment(row.id)
    if (result.code === 200) {
      ElMessage.success('删除评论成功')
      await fetchCommentList()
      // 刷新统计信息
      if (statsRef.value) {
        statsRef.value.refreshStats()
      }
    } else {
      ElMessage.error(result.message || '删除评论失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error)
      ElMessage.error('删除评论失败')
    }
  }
}

// 查看详情
const handleViewDetail = (row) => {
  ElMessageBox.alert(
    `<div style="text-align: left;">
      <p><strong>评论ID：</strong>${row.id}</p>
      <p><strong>评论内容：</strong></p>
      <div style="background: #f5f5f5; padding: 10px; border-radius: 4px; margin: 10px 0; max-height: 200px; overflow-y: auto;">${row.content}</div>
      <p><strong>评论用户：</strong>${row.userName || '未知用户'}</p>
      <p><strong>所属文章：</strong>${row.articleTitle || '未知文章'}</p>
      <p><strong>评论状态：</strong><span style="color: ${getStatusColor(row.status)}">${getStatusText(row.status)}</span></p>
      <p><strong>点赞数：</strong>${row.likeCount || 0}</p>
      <p><strong>创建时间：</strong>${formatDateTime(row.createTime)}</p>
      ${row.parentContent ? `<p><strong>回复评论：</strong>${row.parentContent}</p>` : ''}
    </div>`,
    '评论详情',
    {
      dangerouslyUseHTMLString: true,
      customClass: 'comment-detail-dialog'
    }
  )
}

// 回复评论
const handleReply = (row) => {
  currentComment.value = {
    parentId: row.id,
    articleId: row.articleId,
    parentContent: row.content,
    parentUserName: row.userName
  }
  isEdit.value = false
  editDialogVisible.value = true
}

// 处理更多操作
const handleMoreAction = async (command, row) => {
  try {
    switch (command) {
      case 'reaudit':
        await handleReaudit(row)
        break
      case 'top':
        await handleToggleTop(row, true)
        break
      case 'untop':
        await handleToggleTop(row, false)
        break
      case 'related':
        handleViewRelated(row)
        break
      case 'reports':
        handleViewReports(row)
        break
      case 'delete':
        await handleDelete(row)
        break
      default:
        console.warn('未知操作命令:', command)
    }
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 重新审核
const handleReaudit = async (row) => {
  const { value: status } = await ElMessageBox.prompt(
    '请选择新的审核状态',
    '重新审核',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'select',
      inputOptions: {
        '0': '待审核',
        '1': '已通过',
        '2': '已拒绝'
      },
      inputValue: row.status.toString()
    }
  )
  
  const newStatus = parseInt(status)
  if (newStatus !== row.status) {
    const response = await auditComment(row.id, newStatus)
    if (response.code === 200) {
      ElMessage.success('重新审核成功')
      await fetchCommentList()
      if (statsRef.value) {
        statsRef.value.refreshStats()
      }
    } else {
      ElMessage.error(response.message || '重新审核失败')
    }
  }
}

// 置顶/取消置顶
const handleToggleTop = async (row, isTop) => {
  try {
    const action = isTop ? '置顶' : '取消置顶'
    await ElMessageBox.confirm(`确定要${action}这条评论吗？`, '确认操作', {
      type: 'warning'
    })
    
    const response = await toggleCommentTop(row.id, isTop)
    if (response.code === 200) {
      ElMessage.success(`${action}成功`)
      await fetchCommentList()
      if (statsRef.value) {
        statsRef.value.refreshStats()
      }
    } else {
      ElMessage.error(response.message || `${action}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`操作失败`)
    }
  }
}

// 查看相关评论
const handleViewRelated = (row) => {
  // 跳转到评论页面，筛选同一篇文章的评论
  searchForm.articleId = row.articleId
  searchForm.userId = ''
  searchForm.parentId = ''
  searchForm.status = null
  searchForm.content = ''
  pagination.page = 1
  fetchCommentList()
  ElMessage.success(`已筛选显示文章「${row.articleTitle}」的所有评论`)
}

// 查看举报
const handleViewReports = (row) => {
  ElMessage.info('举报管理功能开发中，敬请期待')
  // TODO: 实现举报查看功能
}

// 获取状态颜色
const getStatusColor = (status) => {
  switch (status) {
    case 0: return '#e6a23c'  // 待审核 - 橙色
    case 1: return '#67c23a'  // 已通过 - 绿色
    case 2: return '#f56c6c'  // 已拒绝 - 红色
    default: return '#909399' // 未知 - 灰色
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的评论')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 条评论吗？\n\n此操作不可恢复！`, 
      '批量删除确认', 
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )
    
    const result = await batchDeleteComments(selectedIds.value)
    if (result.code === 200) {
      ElMessage.success(`批量删除评论成功，共删除 ${selectedIds.value.length} 条`)
      selectedIds.value = []
      await fetchCommentList()
      if (statsRef.value) {
        statsRef.value.refreshStats()
      }
    } else {
      ElMessage.error(result.message || '批量删除评论失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除评论失败:', error)
      ElMessage.error('批量删除评论失败')
    }
  }
}

// 批量审核
const handleBatchAudit = async (status) => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要审核的评论')
    return
  }
  
  const statusText = status === 1 ? '通过' : '拒绝'
  
  try {
    await ElMessageBox.confirm(
      `确定要批量${statusText}选中的 ${selectedIds.value.length} 条评论吗？`, 
      `批量${statusText}确认`, 
      {
        type: 'warning'
      }
    )
    
    // 使用新的批量审核API
    const response = await batchAuditComments(selectedIds.value, status)
    
    if (response.code === 200) {
      ElMessage.success(`批量${statusText}成功，共处理 ${selectedIds.value.length} 条评论`)
      selectedIds.value = []
      await fetchCommentList()
      if (statsRef.value) {
        statsRef.value.refreshStats()
      }
    } else {
      ElMessage.error(response.message || `批量${statusText}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`批量${statusText}失败`)
    }
  }
}

// 批量更多操作
const handleBatchMoreAction = (command) => {
  switch (command) {
    case 'export':
      handleExportSelected()
      break
    case 'move':
      handleBatchMove()
      break
    case 'mark-read':
      handleBatchMarkRead()
      break
    default:
      console.warn('未知批量操作命令:', command)
  }
}

// 导出选中评论
const handleExportSelected = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要导出的评论')
    return
  }
  
  const selectedComments = commentList.value.filter(comment => 
    selectedIds.value.includes(comment.id)
  )
  
  const csvContent = generateCSV(selectedComments)
  downloadCSV(csvContent, `评论导出_${new Date().getTime()}.csv`)
  ElMessage.success(`已导出 ${selectedComments.length} 条评论`)
}

// 导出全部评论
const handleExportAll = () => {
  if (commentList.value.length === 0) {
    ElMessage.warning('暂无数据可导出')
    return
  }
  
  const csvContent = generateCSV(commentList.value)
  downloadCSV(csvContent, `全部评论导出_${new Date().getTime()}.csv`)
  ElMessage.success(`已导出 ${commentList.value.length} 条评论`)
}

// 批量移动
const handleBatchMove = () => {
  ElMessage.info('批量移动功能开发中，敬请期待')
  // TODO: 实现批量移动功能
}

// 批量标记为已读
const handleBatchMarkRead = () => {
  ElMessage.info('批量标记功能开发中，敬请期待')
  // TODO: 实现批量标记功能
}

// 生成CSV内容
const generateCSV = (data) => {
  const headers = ['ID', '评论内容', '用户名', '文章标题', '状态', '点赞数', '创建时间']
  const rows = data.map(item => [
    item.id,
    `"${item.content.replace(/"/g, '""')}"`, // CSV转义
    item.userName || '未知用户',
    item.articleTitle || '未知文章',
    getStatusText(item.status),
    item.likeCount || 0,
    formatDateTime(item.createTime)
  ])
  
  return [headers, ...rows].map(row => row.join(',')).join('\n')
}

// 下载CSV文件
const downloadCSV = (content, filename) => {
  const blob = new Blob([`\uFEFF${content}`], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = filename
  link.click()
  URL.revokeObjectURL(link.href)
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchCommentList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.page = page
  fetchCommentList()
}

// 编辑成功回调
const handleEditSuccess = () => {
  fetchCommentList()
  // 刷新统计数据
  statsRef.value?.refreshStats()
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 组件挂载时获取数据
// 检查配置状态
const checkConfigStatus = async () => {
  try {
    console.log('开始获取配置状态...')
    const response = await getConfigStatus()
    console.log('配置状态响应:', response)
    if (response.code === 200) {
      commentPublishEnabled.value = response.data.commentPublishEnabled
      console.log('配置状态获取成功，评论发布启用状态:', commentPublishEnabled.value)
    } else {
      console.warn('配置状态响应异常:', response)
      // 设置默认值，不阻塞页面加载
      commentPublishEnabled.value = true
    }
  } catch (error) {
    console.error('获取配置状态失败:', error)
    // 设置默认值，不阻塞页面加载
    commentPublishEnabled.value = true
    // 不显示错误消息，避免影响用户体验
  }
}

onMounted(async () => {
  console.log('评论管理页面开始加载...')
  try {
    // 并行执行，不互相阻塞
    await Promise.allSettled([
      fetchCommentList(),
      checkConfigStatus()
    ])
    console.log('评论管理页面加载完成')
  } catch (error) {
    console.error('页面加载过程中出现错误:', error)
  }
})
</script>

<style lang="scss" scoped>
.page-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
  
  .stats-card {
    margin-bottom: 20px;
  }
}

.card-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
    color: #303133;
  }
  
  .search-container {
    margin-bottom: 20px;
    padding: 20px;
    background: #fafafa;
    border-radius: 4px;
  }
  
  .action-container {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 10px;
    
    .batch-actions {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }
    
    .quick-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

// 操作按钮样式
.action-buttons {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
  
  .el-button {
    margin: 0;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    }
    
    &.liked {
      background-color: #f56c6c;
      border-color: #f56c6c;
      color: white;
      
      .el-icon {
        animation: pulse 1s ease-in-out;
      }
    }
  }
  
  .el-dropdown {
    .el-button {
      border: 1px dashed #dcdfe6;
      
      &:hover {
        border-color: #409eff;
        color: #409eff;
      }
    }
  }
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

// 下拉菜单样式
:deep(.el-dropdown-menu) {
  .danger-item {
    color: #f56c6c;
    
    &:hover {
      background-color: #fef0f0;
      color: #f56c6c;
    }
  }
}

// 详情对话框样式
:deep(.comment-detail-dialog) {
  .el-message-box__content {
    text-align: left;
    
    p {
      margin: 8px 0;
      line-height: 1.5;
    }
    
    strong {
      color: #303133;
      font-weight: 600;
    }
  }
}

.el-table {
  .el-table__row {
    .el-button {
      margin-right: 5px;
    }
  }
}

// 用户信息样式
.user-info {
  display: flex;
  align-items: center;
  
  .el-avatar {
    margin-right: 8px;
  }
}

// 文章信息样式
.article-info {
  .article-title {
    font-weight: 500;
    margin-bottom: 4px;
    color: #303133;
  }
  
  .article-category {
    .el-tag {
      font-size: 12px;
    }
  }
}

// 标签容器样式
.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  
  .el-tag {
    margin: 0;
  }
}

.no-tags {
  color: #909399;
  font-size: 12px;
  font-style: italic;
}

// 点赞数样式
.like-count {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #f56c6c;
  
  .el-icon {
    font-size: 14px;
  }
}

// 父评论样式
.parent-comment {
  .parent-user {
    font-weight: 500;
    color: #409eff;
    margin: 0 4px;
  }
  
  .parent-text {
    color: #606266;
    font-size: 12px;
  }
  
  .el-tag {
    margin-right: 8px;
  }
}
</style>
